package com.blog.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.blog.bean.Blog;
import com.blog.bean.BlogMsg;
import com.blog.bean.Share;
import com.blog.bean.User;
import com.blog.dao.IAttentionDao;
import com.blog.dao.IBlogDao;
import com.blog.dao.ICollectionDao;
import com.blog.dao.IComplaintDao;
import com.blog.dao.IDiscussDao;
import com.blog.dao.IPraiseDao;
import com.blog.dao.IRecordDao;
import com.blog.dao.IShareDao;
import com.blog.dao.IUserDao;
import com.blog.util.Result;
import com.blog.util.ResultUtil;

/**
 * @className: LoginController
 * @description: 
 * @author: HCl
 * @createTime: 2020年5月26日 下午10:33:15
 */

@Controller
public class IndexController {
	
	@Autowired
	private IUserDao userDao;
	@Autowired
	private IShareDao shareDao;
	@Autowired
	private IBlogDao blogDao;
	@Autowired
	private IDiscussDao discussDao;
	@Autowired
	private IPraiseDao praiseDao;
	@Autowired
	private IRecordDao recordDao;
	
	
	@RequestMapping(value = "/index")
	
    public String index(HttpSession session) {
		
		
		List<Blog> allBlogs = blogDao.findAllBlogs();
		List<BlogMsg> blogMsgs = new LinkedList<BlogMsg>();
		
		for (int i = 0; i < allBlogs.size(); i++) {
			
			int praise = praiseDao.selectBlogPraiseByBlogId(allBlogs.get(i).getId());
			int recordnum = recordDao.selectRecordByBlogId(allBlogs.get(i).getId());
			int dicussnum = discussDao.selectBlogDiscussById(allBlogs.get(i).getId()).size();
			BlogMsg blogMsg = new BlogMsg(praise, recordnum, dicussnum);
			blogMsgs.add(blogMsg);
		}
		session.setAttribute("all_blog_list", allBlogs);
		session.setAttribute("all_blog_list_msg", blogMsgs);
        return "index";
    }
	
    @RequestMapping("/login")
    public String handleRequest(HttpServletRequest arg0,
            HttpServletResponse arg1) throws Exception {
        return "login";
    }
    
    
    
    @RequestMapping("/upload1")
    public  ResponseEntity<Result> uploadImg(@RequestParam("file") MultipartFile file,
			HttpServletRequest request) throws  IOException {
    	System.out.println("22");
    	String savePath = "/upload/";	
    	//本地使用,上传位置
        //文件的完整名称,如spring.jpeg
        String filename = file.getOriginalFilename();
        //文件名,如spring
        String name = filename.substring(0, filename.indexOf("."));
        //文件后缀,如.jpeg
        String suffix = filename.substring(filename.lastIndexOf("."));
        //创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR)
                + File.separator + (date.get(Calendar.MONTH) + 1));
        //目标文件
        File descFile = new File(savePath + File.separator + dateDirs + File.separator + filename);
        int i = 1;
        //若文件存在重命名
        String newFilename = filename;
        while (descFile.exists()) {
            newFilename = name + "(" + i + ")" + suffix;
            String parentPath = descFile.getParent();
            descFile = new File(parentPath + File.separator + newFilename);
            i++;
        }
        //判断目标文件所在的目录是否存在
        if (!descFile.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
            descFile.getParentFile().mkdirs();
        }
        //将内存中的数据写入磁盘
        file.transferTo(descFile);
        //完整的url
        String fileUrl = "/upload/" + dateDirs + "/" + newFilename;
        System.out.println(fileUrl);
        String[] data = {fileUrl};
        return ResponseEntity.ok().body(new Result(1,data));
    }
    
    @RequestMapping(value = "/upload", produces = {"text/html;charset=UTF-8"},method=RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestPart("files") List<MultipartFile> files, HttpServletRequest request) {
        //获取文件上传目录
        String path= getClass().getResource("/").getPath();
        path= path+"upload"+File.separator+"uploadfiles";
        if(files != null && files.size() > 0){
            //封装返回数据
            Map<String, Object> map = new HashMap<>();
            String imgUrls[] = new String[files.size()];
            for (int i=0; i<files.size(); i++) {
                //获取文件扩展名
                String extName = FilenameUtils.getExtension(files.get(i).getOriginalFilename());
                //生成新的文件名
                String fileName = UUID.randomUUID().toString() + FilenameUtils.EXTENSION_SEPARATOR + extName;
                //创建空文件对象
                File targetFile = new File(path, fileName);
                // 检测是否存在目录
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                //上传图片
                try {
                    files.get(i).transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //拼装上传后的图片地址
                String url = request.getContextPath() + "/upload/uploadfiles/" + fileName;
                //存储到字符串数组
                imgUrls[i] = url;
            }
            map.put("error",0);
            map.put("data", imgUrls);
            return JSON.toJSONString(map);
        }
        return null;
    }

}
